import axios from "axios";
import QS from "qs";
import { Toast } from "vant";
import store from "../store/index";
import router from "../router/index";

if (process.env.NODE_ENV === "development") {
  axios.defaults.baseURL = "https://www.development.com";
} else if (process.env.NODE_ENV === "debug") {
  axios.defaults.baseURL = "https://ceshi.com";
} else if (process.env.NODE_ENV === "production") {
  axios.default.baseURL = "https://www.prduction.com";
}

axios.defaults.timeout = 10000;

axios.defaults.headers.post["Content-Type"] =
  "application/x-www-from-urlencoded;charset=UTF-8";

axios.interceptors.request.use(config => {
  const token = store.state.token;
  token && (config.headers.Authorization = token);
  return config;
});

axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return PromiseRejectionEvent.reject(response);
    }
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          router.replace({
            path: "/login",
            query: {
              redirect: router.currentRoute.fullPath
            }
          });
      }
    }
  }
);

export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}

export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, QS.stringify(params))
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
